package com.h2cloud.workflow;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author: wulongkai
 * @create: 2022-11-23 16:25
 **/
public class Main {
    public static void main(String[] args) {
        ExecutorService EXECUTOR_SERVICE = new MonitorTreadPoolExecutor(15, 30, 60L,
                TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), r -> new Thread(r, "工作流异步任务"));

        ExecutorService EXECUTOR_WORKFLOE_SERVICE = new MonitorTreadPoolExecutor(15, 30, 60L,
                TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024), r -> new Thread(r, "工作流自动节点异步执行"));

        List<CompletableFuture> futures = new ArrayList<>();
        List<Runnable> runnableList = new ArrayList<>();
        List<Runnable> afterRunnableList = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            int val = i;
            runnableList.add(() -> {
                System.out.println("before: " + val);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        for (int i = 0; i < 5; i++) {
            int val = i;
            afterRunnableList.add(() -> {
                System.out.println("after: " + val);
                try {
                    if (val == 0) {
                        Thread.sleep(5000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        long l = System.currentTimeMillis();
        runnableList.forEach(run -> futures.add(CompletableFuture.runAsync(run, EXECUTOR_WORKFLOE_SERVICE)));
        CompletableFuture f = CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{}));
        for (Runnable a : afterRunnableList) {
            f = f.thenRunAsync(a, EXECUTOR_SERVICE);
        }
        f.join();
        System.out.println("WorkFlowBaseService getWorkFlowAndCurrentNode await cost:" + (System.currentTimeMillis() - l));
    }
}
